<?php
namespace Home\Controller;
use Home\Controller\WxhelperController;
class WxpayController extends WxhelperController{
    protected  $parameters=array();//请求参数，类型为关联数组
    public function Wxpay(){
        $this->setParameters('nonce_str', $this->getNoncestr());//随机字符串
        $this->setParameters('mch_billno', C('MCHID').date("YmdHis").rand(1000, 9999));//商户订单号
        $this->setParameters('mch_id', C('MCHID'));//商户号
        $this->setParameters('wxappid', C('APPID'));//公众号appid
        $this->setParameters('send_name', '数巨云');//发送方的名字
        $this->setParameters('re_openid', 'oFZMcw62TmOMGp0ki-WER8vRfVeU');//接收用户的openid
        $this->setParameters('total_amount', 100);//付款金额 单位是分
        $this->setParameters('total_num', 1);//发放人总数
        $this->setParameters('wishing', '新年快乐');//红包祝福语
        $this->setParameters('client_ip', '60.205.24.136');//调用接口的ip地址
        $this->setParameters('act_name', '问卷有奖调查');//活动名称
        $this->setParameters('remark', '随机红包');//备注
       // $this->setParameters('scene_id', 'PRODUCT_2');//发放红包使用场景，红包金额大于200时必传
        //获取签名
        $sign=$this->getSign($this->parameters);
        $this->setParameters('sign', $sign);
        //生成xml
        $postxml=$this->arrayToxml($this->parameters);
       // 接口地址
        $url="https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
        //curl--post
        $xml=$this->postXmlCurl($postxml, $url,true);//返回的数据是xml
        //将xml数据转换成数组
        //交易是否成功需要查看result_code来判断
        $result=$this->xmlToarray($xml);
        if(strtolower($result['result_code'])=='success'){
            $data['mch_billno']=$result['mch_billno'];
            $data['openid']=$result['openid'];
            if($this->save_packet_record($data)){
               $this->redirect(""); 
            }
               
        }
    
    }
    /**
     * 红包发放记录查询
     */
    public  function  packetRecord(){
        $this->setParameters('nonce_str', $this->getNoncestr());//随机字符串
        $this->setParameters('mch_billno', '1382093902201702200936336956');//商户订单号
        $this->setParameters('mch_id', C('MCHID'));//商户号
        $this->setParameters('appid',C('APPID'));//公众号appid
        $this->setParameters('bill_type', 'MCHT');//MCHT:通过商户订单号获取红包信息
        //获取签名
        $sign=$this->getSign($this->parameters);
        $this->setParameters('sign', $sign);
        //生成xml
        $postxml=$this->arayToxml($this->parameters);
        //curl--post
        $url="https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo";
       // $res=$this->postXmlCurl($postxml, $url,true);
      //  dump($res);
        
    }
    /**
     * 保存用户红包领取成功之后的订单记录
     * @param mobileNum 
     * @param mch_billno
     */
    public function save_packet_record($data){
       return M("record")->data($data)->add();
    }
    /**
     * 以post方式提交xml到对应的接口url
     *
     * @param string $xml  需要post的xml数据
     * @param string $url  url
     * @param bool $useCert 是否需要证书，默认不需要
     * @param int $second   url执行超时时间，默认30s
     * @throws WxPayException
     */
    private static function postXmlCurl($xml, $url, $useCert = false, $second = 30)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
    
        //如果有配置代理这里就设置代理
        if(C('CURL_PROXY_HOST') != "0.0.0.0"
            && C('CURL_PROXY_PORT') != 0){
            curl_setopt($ch,CURLOPT_PROXY, C('CURL_PROXY_HOST'));
            curl_setopt($ch,CURLOPT_PROXYPORT, C('CURL_PROXY_PORT'));
        }
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//严格校验
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    
        if($useCert == true){
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLCERT,getcwd().C('SSLCERT_PATH'));
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLKEY,getcwd().C('SSLKEY_PATH'));
            curl_setopt($ch,CURLOPT_CAINFO, 'PEM');
            curl_setopt($ch,CURLOPT_CAINFO,getcwd().C('CA_PATH'));
            
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            E("curl出错，错误码:$error");
        }
    } 
    /**
     * 设置请求参数
     */
    public function  setParameters($parameter,$parametervalue){
        $this->parameters[$this->trimString($parameter)]=$this->trimString($parametervalue);
    }
    public function getParameters($parameter){
        return $this->parameters[$parameter];
    }
    public function checkSignParameters($parameter){
        foreach ($this->getParameters($parameter) as $k=>$v){
            if($this->parameters[$k]==null){
                return false;
            }   
        }
        return true;
    }
    /**
     * 获取签名sign
     */
    public function getSign($obj){
        foreach ($obj as $k=>$v){
            $paramters[$k]=$v;
        }
        //对参数按照key=value的格式，并按照参数名ASCII字典序排序
        ksort($paramters);
        $string=$this->formatBizQueryParaMap($paramters, false);
        //拼接api密钥
        $string=$string."&key=".C('KEY');
        //MD5加密
        $string=md5($string);
        //大写
        $result=strtoupper($string);
        return $result;
    }
    
}